package leetcode.erfen;

public class Test1 {
    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int[] searchRange = searchRange(nums, 8);
        for (int i = 0; i < searchRange.length; i++) {
            System.out.println(searchRange[i]);
        }
    }

    public static int binarySearch(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int mid = 0;
        while (left < right) {
            mid = (right + left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return mid;
    }

    public static int[] searchRange(int[] nums, int target) {
        int leftIdx = binarySearch(nums, target, true);
        int rightIdx = binarySearch(nums, target, false) - 1;
        return new int[]{leftIdx, rightIdx};
    }

    private static int binarySearch(int[] nums, int target, boolean lower) {
        int left = 0, right = nums.length - 1, ans = nums.length;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target || (lower && nums[mid] >= target)) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}
